package JavaStructure.Other;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class SparseArray {
    public static void main(String[] args) {
        //制作演示列表
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入预设");

        int i = sc.nextInt();
        int[][] array1 = new int[i][i];

        //实现随机布局
        Random ra = new Random();
        int b = ra.nextInt(1,(int)Math.pow(i,2));//随即个数个棋子
        for(int a = 0;a < b;a++){
            int k = ra.nextInt(1,3);//黑白子
            //位置
            int x = ra.nextInt(1,i);
            int y = ra.nextInt(1,i);
            array1[x][y] = k;
        }

        //遍历预设数组并计数
        int count = 0;
        for(int[] array2 : array1) {
            System.out.println(Arrays.toString(array2));
            for(int j = 0;j < array2.length;j++){
                if(array2[j] != 0){
                    count++;
                }
            }
        }

        //创建稀疏数组
        int[][] array3 = new int[count + 1][3];
        array3[0][0] = i;
        array3[0][1] = i;
        array3[0][2] = count;
        for(int d = 0;d < array1.length;d++) {
            for(int j = 0;j < array1[d].length;j++){
                if(array1[d][j] != 0){
                    array3[count][2] = array1[d][j];
                    array3[count][1] = j;
                    array3[count][0] = d;
                    count--;
                }
            }
        }


        System.out.println(Arrays.deepToString(reverseRows(array3)));

    }
    //翻转数组
    public static int[][] reverseRows(int[][] array) {
        // 处理空数组或无效输入
        if (array == null || array.length == 0) return new int[0][0];

        int rows = array.length;    // 总行数
        int cols = array[0].length; // 总列数（假设每行列数相同）
        int[][] reversed = new int[rows][cols];

        // 逆序复制行：新数组的第i行 = 原数组的第rows-1-i行
        for (int i = 1; i < rows; i++) {
            reversed[i] = array[rows - 1 - i];
        }

        return reversed;
    }
}

